﻿Imports System.ServiceModel.DomainServices.Client

Partial Public Class NetejaEntradaSortida
    Inherits ChildWindow

    Private _Neteja As Web.Neteja
    Public ReadOnly Property Neteja As Web.Neteja
        Get
            Return _Neteja
        End Get
    End Property

    Private _Mode As EnumMode
    Public ReadOnly Property Mode As EnumMode
        Get
            Return _Mode
        End Get
    End Property

    Private _HostalActual As Web.Hostal
    Private ReadOnly Property HostalActual
        Get
            If Neteja Is Nothing Then
                Return _HostalActual
            Else
                Return Neteja.Hostal
            End If
        End Get
    End Property

    Public Enum EnumMode
        ModeEntrada
        ModeSortida
    End Enum

#Region "Crear i Destruir"
    Public Sub New(pMode As EnumMode)
        MyBase.New()

        InitializeComponent()
        _Mode = pMode
    End Sub

    Public Sub New(pMode As EnumMode, pNeteja As Web.Neteja)
        Me.New(pMode)
        _Neteja = pNeteja
    End Sub

    Private Sub Child_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        Application.Current.RootVisual.SetValue(Control.IsEnabledProperty, True)
    End Sub

    Private Sub NetejaAlta_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        If RiaContext.Current.Authentication.User.Identity.IsAuthenticated = True Then
            If HostalActual Is Nothing Then
                If Contexte.HostalsPerUsuariActual.Count = 1 Then
                    _HostalActual = Contexte.HostalsPerUsuariActual.FirstOrDefault
                    FormLoadedIHostalTriat()
                Else
                    Dim input As InputComboWindow = New InputComboWindow(My.Resources.StringLibrary.EscojaUnHostal, Contexte.HostalsPerUsuariActual, "Nom")
                    AddHandler input.Closed, AddressOf TriarHostal
                    input.Show()
                End If
            Else
                FormLoadedIHostalTriat()
            End If
        End If
    End Sub

    Private Sub TriarHostal(sender As System.Object, e As System.EventArgs)
        Dim Input As InputComboWindow = DirectCast(sender, InputComboWindow)
        RemoveHandler Input.Closed, AddressOf TriarHostal

        If Input.DialogResult = False OrElse Input.SelectedItem Is Nothing Then
            Me.DialogResult = False
        Else
            _HostalActual = Input.SelectedItem
            FormLoadedIHostalTriat()
        End If
    End Sub

    Private Sub FormLoadedIHostalTriat()
        Me.Activity.IsActive = True

        If Neteja Is Nothing Then
            Dim IdUsuari As Integer = -1

            If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Neteja Then IdUsuari = Contexte.UsuariActual.Id

            Contexte.DomainContext.Load(LullabyFullDeCaixa.Contexte.DomainContext.GetNetejaObertaHostalQuery(HostalActual.Id, Date.SpecifyKind(Now.Date, DateTimeKind.Utc), IdUsuari), _
               New Action(Of LoadOperation(Of LullabyFullDeCaixa.Web.Neteja))(AddressOf NetejaLoaded), _
               Nothing)
        Else
            _Neteja.IdUsuariTancament = Contexte.UsuariActual.Id
            _Neteja.HoraTancament = Now.TimeOfDay
            Me.gridDetall.DataContext = _Neteja
            _NetejaLoaded = True
        End If

        AddHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats
        Contexte.LoadUsuaris()

        BloquejarCamps()
    End Sub

    Private Sub BloquejarCamps()
        Select Case Mode
            Case EnumMode.ModeEntrada
                Me.Title = StringLibrary.AltaNeteja

                lblHoraTancament.Visibility = Windows.Visibility.Collapsed
                txtHoraFi.Visibility = Windows.Visibility.Collapsed

                If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Neteja Then cboPersonalNeteja.IsEnabled = False

            Case EnumMode.ModeSortida
                Me.Title = StringLibrary.TancarNeteja

                cboPersonalNeteja.IsEnabled = False
                txtHoraInici.IsEnabled = False

        End Select
    End Sub
#End Region

#Region "Carregar Dades"
    Private _UsuarisLoaded As Boolean = False
    Private _NetejaLoaded As Boolean = False

    Private Sub UsuarisCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats

        _UsuarisLoaded = True

        Dim DadesUsuariNeteja As List(Of Web.Usuari) = Nothing
        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Neteja Then
            DadesUsuariNeteja = New List(Of Web.Usuari)({Contexte.UsuariActual})
        Else
            DadesUsuariNeteja = (From UH As Web.UsuariHostal In Contexte.DomainContext.UsuariHostals Where UH.Usuari.IdTipusUsuari = EnumTipusUsuari.Neteja AndAlso UH.Hostal Is HostalActual Select UH.Usuari Order By Usuari.Nom).ToList
        End If
        Me.cboPersonalNeteja.ItemsSource = DadesUsuariNeteja

        If _UsuarisLoaded And _NetejaLoaded Then Me.Activity.IsActive = False

    End Sub

    Private Sub NetejaLoaded(ByVal LListaNeteja As LoadOperation(Of LullabyFullDeCaixa.Web.Neteja))
        'Un cop carregat ho guardem en una llista
        _NetejaLoaded = True

        If LListaNeteja.HasError Then
            App.ReportError(StringLibrary.ErrorCarregantDades)
        Else
            Select Case Mode
                Case EnumMode.ModeEntrada
                    If LListaNeteja.Entities.Count > 0 Then
                        'Missatge d'error
                        If MessageBox.Show(StringLibrary.JaHiHaUnaNetejaPerAquestHostal, StringLibrary.Informacio, MessageBoxButton.OKCancel) = MessageBoxResult.Cancel Then
                            Me.DialogResult = False
                        End If
                    End If
                    _Neteja = New LullabyFullDeCaixa.Web.Neteja() With {.Data = Date.SpecifyKind(Now.Date, DateTimeKind.Utc), .HoraObertura = Now.TimeOfDay, .IdUsuariObertura = Contexte.UsuariActual.Id, .Hostal = HostalActual}
                    If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Neteja Then _Neteja.IdUsuariNeteja = Contexte.UsuariActual.Id
                    Me.gridDetall.DataContext = _Neteja

                Case EnumMode.ModeSortida
                    If LListaNeteja.Entities.Count = 1 Then
                        'Una sola neteja
                        _Neteja = LListaNeteja.Entities.FirstOrDefault
                        _Neteja.IdUsuariTancament = Contexte.UsuariActual.Id
                        _Neteja.HoraTancament = Now.TimeOfDay
                        Me.gridDetall.DataContext = _Neteja

                    ElseIf LListaNeteja.Entities.Count = 0 Then
                        'Cap neteja, missatge d'error
                        App.ShowMessage(StringLibrary.NoHiHaUnaNetejaPerAquestHostal)
                        Me.DialogResult = False

                    Else
                        'Més d'una neteja, s'ha de triar
                        Dim child As InputComboWindow = New InputComboWindow(StringLibrary.EscojaUnaLimpieza, LListaNeteja.Entities.ToList(), "UsuariNeteja.Nom")
                        AddHandler child.Closed, AddressOf TriarNeteja
                        child.Show()
                    End If
            End Select
        End If

        If _UsuarisLoaded And _NetejaLoaded Then Me.Activity.IsActive = False
    End Sub

    Private Sub TriarNeteja(sender As System.Object, e As System.EventArgs)
        Dim Input As InputComboWindow = DirectCast(sender, InputComboWindow)
        RemoveHandler Input.Closed, AddressOf TriarNeteja

        If Input.DialogResult = False OrElse Input.SelectedItem Is Nothing Then
            Me.DialogResult = False
        Else
            _Neteja = Input.SelectedItem
            _Neteja.IdUsuariTancament = Contexte.UsuariActual.Id
            _Neteja.HoraTancament = Now.TimeOfDay
            Me.gridDetall.DataContext = _Neteja
        End If


    End Sub
#End Region

#Region "Guardar i Cancelar"
    Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        EliminarObjectErrors()

        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            If ValidarDades() And Validacio.Errors.Count = 0 Then
                LullabyFullDeCaixa.Contexte.DomainContext.SubmitChanges(AddressOf DomainContext_SubmittedChanges, Nothing)
                Activity.IsActive = True
            End If
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Function ValidarDades() As Boolean
        Dim Resultat As Boolean = True

        If Neteja.UsuariNeteja Is Nothing Then
            Validacio.Errors.Add(New ValidationSummaryItem(StringLibrary.DebeSeleccionarUnUsuarioLimpieza))
            Resultat = False
        End If

        If Mode = EnumMode.ModeSortida AndAlso Not Neteja.HoraTancament.HasValue Then
            Validacio.Errors.Add(New ValidationSummaryItem(StringLibrary.HoraSalidaNoValida))
            Resultat = False
        End If

        Return Resultat
    End Function

    Private Sub DomainContext_SubmittedChanges(ByVal s As SubmitOperation)
        Activity.IsActive = False

        If s.HasError Then
            App.ReportError(StringLibrary.ErrorGuardantDades)
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            LullabyFullDeCaixa.Contexte.DomainContext.RejectChanges()
        End If

        Me.DialogResult = False
    End Sub

    Public Sub EliminarObjectErrors()
        Dim i As Long

        i = 0
        While i < Validacio.Errors.Count
            If Validacio.Errors(i).ItemType = ValidationSummaryItemType.ObjectError Then
                Validacio.Errors.RemoveAt(i)
            Else
                i = i + 1
            End If
        End While
    End Sub
#End Region


End Class
